// handlers/article_list.go
package handlers

import (
	"net/http"
	"strconv"

	"go.mongodb.org/mongo-driver/bson/primitive"

	"zwai-app/services"
	"zwai-app/util"
)

// publicArticlesHandler 处理 GET /articles/public?page=1&size=10&categoryId=...
func publicArticlesHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}

	// 解析分页参数
	q := r.URL.Query()
	page, _ := strconv.Atoi(q.Get("page"))
	if page < 1 {
		page = 1
	}
	size, _ := strconv.Atoi(q.Get("size"))
	if size < 1 {
		size = 10
	}

	// 解析可选 categoryId
	var catID *primitive.ObjectID
	if cid := q.Get("categoryId"); cid != "" {
		if oid, err := primitive.ObjectIDFromHex(cid); err == nil {
			catID = &oid
		}
	}

	// 调用 Service
	result, err := services.GetPublicArticlesPage(r.Context(), page, size, catID)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{
			"code": 2, "msg": "查询失败: " + err.Error(),
		})
		return
	}

	// 返回分页数据
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{
		"code": 0,
		"msg":  "查询成功",
		"data": result,
	})
}

func hotArticlesHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}
	// 解析 limit 参数，默认 10
	limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
	if limit <= 0 {
		limit = 10
	}
	list, err := services.GetHotArticles(r.Context(), limit)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 2, "msg": "查询失败: " + err.Error()})
		return
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "查询成功", "data": list})
}

// allArticlesHandler 处理 GET /articles/all?page=1&size=10
func allArticlesHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		util.JSONResponse(w, http.StatusNotFound, map[string]interface{}{"code": 1, "msg": "接口不存在"})
		return
	}
	q := r.URL.Query()
	page, _ := strconv.Atoi(q.Get("page"))
	if page < 1 {
		page = 1
	}
	size, _ := strconv.Atoi(q.Get("size"))
	if size < 1 {
		size = 10
	}

	var catID *primitive.ObjectID
	if cid := q.Get("categoryId"); cid != "" {
		if oid, err := primitive.ObjectIDFromHex(cid); err == nil {
			catID = &oid
		}
	}
	// cid := r.URL.Query().Get("categoryId")
	// fmt.Println("🔍 Raw categoryId query param:", cid)
	// fmt.Println("🔍 Parsed catID pointer is nil?", cid == "" || catID == nil)
	// fmt.Println("🔍 Parsed catID pointer is nil?", catID == nil)

	result, err := services.GetAllArticlesPage(r.Context(), page, size, catID)
	if err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{"code": 2, "msg": "查询失败: " + err.Error()})
		return
	}
	util.JSONResponse(w, http.StatusOK, map[string]interface{}{"code": 0, "msg": "查询成功", "data": result})
}
